package com.zy.chat.mq;


import com.alibaba.fastjson.JSON;
import com.zy.chat.constants.constants;
import com.zy.chat.entity.SingleMessages;
import com.zy.chat.mapper.SingleMessageMapper;
import com.zy.chat.service.SaveSingleMessageService;
import com.zy.chat.vo.SinglemsgsDoc;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class SingleMsgListener {

    @Autowired
    private SingleMessageMapper singleMessageMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = constants.INSERT_QUEUE_NAME_SINGLEMSG,durable = "true"),
            exchange = @Exchange(name=constants.EXCHANGE_NAME_SINGLEMSG,durable = "tru1e",type = ExchangeTypes.TOPIC),
            key=constants.INSERT_KEY_SINGLEMSG
    ))
    public void listenSinglemsgInsert(SingleMessages singleMessages){

            singleMessageMapper.insert(singleMessages);
                //转换文档
            SinglemsgsDoc singlemsgsDoc=new SinglemsgsDoc(singleMessages);
            IndexRequest request = new IndexRequest("singlemsg").id(singleMessages.getId().toString());
            request.source(JSON.toJSONString(singlemsgsDoc), XContentType.JSON);
            try {
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                throw new RuntimeException("新增单聊消息失败");
            }
    }
}
